<template>
	<view class="content">
		<view class="text-area">
			<text class="title"></text>
		</view>
		<unicloud-db v-slot:default="{data, loading, error, options}" collection="opendb-vote-question" gettree field="_id as value,text,anonymous,deadline,is_other,is_radio">
			<view v-if="error">{{error.message}}</view>
			<view v-else>
				<!-- {{data}} -->
				<uni-forms ref="form" :value="formData" @submit="submit">
					<view v-for="(item,index) in data" :key="index">
						问题：{{item.text}}
						<uni-forms-item :name="item._id" required>
							<uni-data-checkbox :multiple="!item.is_radio" :localdata="item.children" />
						</uni-forms-item>
					</view>
				</uni-forms>
			</view>
		</unicloud-db>

		<button type="primary" class="uni-button" style="width: 100px;" @click="submitForm">提交</button>
	</view>
</template>

<script>
	const db = uniCloud.database()
	export default {
		data() {
			return {
				formData: {
					"arr_result": [{
						"question_id": "",
						"result_id": []
					}, {
						"question_id": "",
						"result_id": []
					}]
				}
			}
		},
		onLoad() {

		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submitForm(form) {
				this.$refs.form.submit();
			},

			/**
			 * 表单提交
			 * @param {Object} event 回调参数 Function(callback:{value,errors})
			 */
			submit(event) {
				const {
					value,
					errors
				} = event.detail
				console.log("value: ", value);
				db.collection("opendb-vote-log").add({"arr_result": value}).then((res) => {
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
